<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
    <style>
      * {
        margin: 0;
        padding: 0;
        background-color: #333;
      }
    </style>
  </head>
  <body>
    <script>
      const jsonData = '{"title": "hello", "age": 18}';
      const parseJSONData = JSON.parse(jsonData);

      const obj = {
        title: 'hello',
        age: 18,
      };

      const objProxy = new Proxy(obj, {
        // receiver:代理对象
        get(target, key, receiver) {
          console.log('监听:监听到title的获取', `target:`, target, `key:`, key);
          return target[key];
        },
        set(target, key, newValue, receiver) {
          console.log(
            '监听:监听到title的设置',
            `target:`,
            target,
            `key:`,
            key,
            `newValue:`,
            newValue
          );
          target[key] = newValue;
        },
      });

      const parseJSONDataProxy = new Proxy(parseJSONData, {
        // receiver:代理对象
        get(target, key, receiver) {
          console.log('监听:监听到title的获取', `target:`, target, `key:`, key);
          return target[key];
        },
        set(target, key, newValue, receiver) {
          console.log(
            '监听:监听到title的设置',
            `target:`,
            target,
            `key:`,
            key,
            `newValue:`,
            newValue
          );
          target[key] = newValue;
        },
      });

      console.log(objProxy.title);
      objProxy.title = 'world';
      console.log(objProxy.title);
      objProxy.address = '拆那 China';

      console.log('-------------------------------------------------');

      console.log(parseJSONDataProxy.title);
      parseJSONDataProxy.title = 'world';
      console.log(parseJSONDataProxy.title);
      parseJSONDataProxy.address = '拆那 China';
    </script>
  </body>
</html>
